package com.echo.im.client.config;

import com.echo.im.client.status.listener.UserStatusListener;
import com.echo.im.common.contant.RedisConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * Redis 订阅配置，用于监听这个用户上下线状态
 * @author echo
 */
@Configuration
public class RedisSubscriberConfig {

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 订阅 "IM_USER_STATUS_CHANNEL" 频道
        container.addMessageListener(listenerAdapter, new PatternTopic(RedisConstants.IM_USER_STATUS_CHANNEL));
        return container;
    }

    @Bean
    public MessageListenerAdapter listenerAdapter(UserStatusListener listener) {
        return new MessageListenerAdapter(listener, "onMessage");
    }
}
